package com.lagou.sqlSession;

import com.lagou.pojo.Configuration;
import com.lagou.pojo.MappedStatement;

import java.lang.reflect.*;
import java.util.List;
import java.util.Map;


/**
 * @author sintang
 * @date 2020-09-02 22
 */
public class DefaultSqlSession implements SqlSession {
    private Configuration configuration;

    public DefaultSqlSession(Configuration configuration) {
        this.configuration = configuration;
    }

    /**
     * 查询列表
     *
     * @param statementId
     * @param params
     * @return
     */
    @Override
    public <E> List<E> selectList(String statementId, Object... params) throws Exception {
        SimpleExecutor simpleExecutor = new SimpleExecutor();
        Map<String, MappedStatement> mappedStatementMap = configuration.getMappedStatementMap();
        List<Object> list = simpleExecutor.query(configuration, mappedStatementMap.get(statementId), params);


        return (List<E>) list;
    }

    /**
     * 查询单一对象
     *
     * @param statementId
     * @param params
     * @return
     */
    @Override
    public <E> E selectOne(String statementId, Object... params) throws Exception {
        List<Object> list = selectList(statementId, params);
        if(list.size() > 1){
            throw new RuntimeException("返回多条数据");
        }
        if(list.size() == 1){
            return (E) list.get(0);
        }
        return null;
    }

    @Override
    public void insert(String statementId, Object... params) throws Exception {
        SimpleExecutor simpleExecutor = new SimpleExecutor();
        Map<String, MappedStatement> mappedStatementMap = configuration.getMappedStatementMap();
        simpleExecutor.insert(configuration,mappedStatementMap.get(statementId),params);
    }

    @Override
    public void update(String statementId, Object... params) throws Exception {
        SimpleExecutor simpleExecutor = new SimpleExecutor();
        Map<String, MappedStatement> mappedStatementMap = configuration.getMappedStatementMap();
        simpleExecutor.update(configuration,mappedStatementMap.get(statementId),params);
    }

    @Override
    public void delete(String statementId, Object... params) throws Exception {
        SimpleExecutor simpleExecutor = new SimpleExecutor();
        Map<String, MappedStatement> mappedStatementMap = configuration.getMappedStatementMap();
        simpleExecutor.delete(configuration,mappedStatementMap.get(statementId),params);
    }

    /**
     * 为dao接口生成代理实现类
     *
     * @param mapperClass
     * @return
     */
    @Override
    public <T> T getMapper(Class<?> mapperClass) {
        Object proxyInstance = Proxy.newProxyInstance(DefaultSqlSession.class.getClassLoader(), new Class[]{mapperClass}, new InvocationHandler() {
            @Override
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                // 先获取到mapperClass对应的xml文件，xml的namespace要和接口class全路径一样
                // 找到对应的 statement.id = className + methodName
                String className = method.getDeclaringClass().getName();
                String methodName = method.getName();
                String statementId = className + "." + methodName;

                // 在这里增加根据statementId判断是什么操作类型
                switch (configuration.getMappedStatementTypeMap().get(statementId)){
                    case select:
                        // 根据返回值类型判断调用哪个方法
                        Type genericReturnType = method.getGenericReturnType();
                        // 是否适用了泛型参数
                        if(genericReturnType instanceof ParameterizedType){
                            List<Object> objects = selectList(statementId, args);
                            return objects;
                        }

                        return selectOne(statementId,args);
                    case insert:
                        insert(statementId,args);
                        break;
                    case update:
                        update(statementId,args);
                        break;
                    case delete:
                        delete(statementId,args);
                        break;
                    default:
                        System.out.println("未识别操作类型");
                        throw new RuntimeException("未识别操作类型");
                }

                return null;
            }
        });
        return (T) proxyInstance;
    }
}
